package com.corner.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.corner.common.exception.GlobalException;
import com.corner.common.utils.WXPayUtil;
import com.corner.system.domain.CtrMsg;
import com.corner.system.service.ISysControlService;
import com.corner.system.websocket.WebSocketClientHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @program: ruoyi
 * @description: 控制服务
 * @author: lydms
 * @create: 2024-07-05 10:46
 **/
@Service
public class ISysControlServiceImpl implements ISysControlService {

    public static String sessionId = null;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private WebSocketClientHandler webSocketClientHandler;



    @Override
    public void sendControlMsg(Map map) {
        String topic = (String)map.get("topic");
        String dataStr = (String)map.get("data");
        Map<String,String> data = JSON.parseObject(dataStr, Map.class);
        String[] split = topic.split("/");
        String s = split[3];

        String stationId = s.substring(14);
        System.out.println(stationId);

        CtrMsg ctrMsg = new CtrMsg();
        for(Map.Entry entry : data.entrySet()){
            String mapKey = (String) entry.getKey();
            String mapValue = (String)entry.getValue();
            System.out.println(mapKey+":"+mapValue);
            ctrMsg.setStationId(stationId);
            ctrMsg.setDeviceId(mapKey);
            ctrMsg.setValue(mapValue);
        }

        try {

            webSocketClientHandler.sendMessage(ctrMsg);

        } catch (Exception e) {
            e.printStackTrace();
            throw new GlobalException(e.getMessage());
        }


    }

    public static void main(String[] args) {
        Date date = new Date();
        long time = date.getTime();
        Map v = new LinkedHashMap();
        v.put("username","admin");


        v.put("__time__",time+"");
        String vs = null;

        try {
//            vs = WXPayUtil.mapToXmlNoHead(v,false);
            vs = WXPayUtil.mapToXml(v);
            System.out.println(vs);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
